package com.retoc.oawx.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateRange;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retoc.oawx.domain.Leave;
import com.retoc.oawx.exception.OAException;
import com.retoc.oawx.mapper.HolidaysMapper;
import com.retoc.oawx.mapper.UserMapper;
import com.retoc.oawx.mapper.WorkdayMapper;
import com.retoc.oawx.service.ApproveService;
import com.retoc.oawx.service.LeaveService;
import com.retoc.oawx.mapper.LeaveMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
* @author retoc
* @description 针对表【tb_leave】的数据库操作Service实现
* @createDate 2022-06-12 11:10:24
*/
@Service
public class LeaveServiceImpl extends ServiceImpl<LeaveMapper, Leave>
    implements LeaveService{

    @Autowired
    private LeaveMapper leaveMapper;

    @Autowired
    private HolidaysMapper holidaysMapper;

    @Autowired
    private WorkdayMapper workdayMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ApproveService approveService;

    @Value("${oawx.receiveNotify}")
    private String receiveNotify;

    @Value("${workflow.urla}")
    private String workflow;

    @Override
    public void insertLeave(Leave leave) {
//        Date startTime = leave.getStartTime();
//        Date endTime = leave.getEndTime();
//        Date start = leave.getStart();
        DateTime start = DateUtil.parseDate(leave.getStart());
        DateTime end = DateUtil.parseDate(leave.getEnd());
        DateTime startTime = DateUtil.parseTime(leave.getStartTime());
        DateTime endTime = DateUtil.parseTime(leave.getEndTime());
        int hour=endTime.hour(true)-startTime.hour(true)-2;
        HashMap param=new HashMap<>();
        param.put("startDate", start.toString());
        param.put("endDate", end.toString());
        ArrayList<String> holidayList = holidaysMapper.searchHolidaysInRange(param);
        ArrayList<String> workdayList = workdayMapper.searchWorkdayInRange(param);
        AtomicInteger i= new AtomicInteger();
//        Date end = leave.getEnd();

        SimpleDateFormat fmt=new SimpleDateFormat("yyyyMMdd");
        if (!fmt.format(start).equals(fmt.format(end))){
            DateRange range = DateUtil.range(start, end, DateField.DAY_OF_MONTH);
            range.forEach(one-> {
                String date = one.toString("yyyy-MM-dd");
                //初始化type为工作日
                String type = "工作日";
                //如果为周末则改成节假日
                if (one.isWeekend()) {
                    type = "节假日";
                }
                //如果之前查询的特殊假日表中含有当天，则必定为节假日
                if (holidayList != null && holidayList.contains(date)) {
                    type = "节假日";
                }
                //如果之前查询的特殊工作日表中含有当天，则必定为工作日
                else if (workdayList != null && workdayList.contains(date)) {
                    type = "工作日";
                }
                if (type.equals("工作日")){
                    i.getAndIncrement();
                }
            });
        }
        hour=hour+i.get()*8;
        leave.setHour(hour);
        int day=i.get()+1;

        int row = leaveMapper.insertLeave(leave);
        if (row!=1){
            throw new OAException("请假单提交失败");
        }
//        startLeaveWorkFlow(leave.getUuid(),leave.getCreatorId().intValue(),leave.getDate(),leave.getStart());
//        startLeaveWorkFlow(int creatorId,String start,int day,String uuid)
        startLeaveWorkFlow(leave.getCreatorId(),leave.getStart(),day,leave.getUuid());
    }

    @Override
    public ArrayList<HashMap> selectLeaveListByCreator(HashMap param) {
        return leaveMapper.selectLeaveListByCreator(param);
    }

    @Override
    public ArrayList<HashMap> selectoldLeaveListByCreator(HashMap param) {
        return leaveMapper.selectOldLeaveListByCreator(param);
    }

    @Override
    public HashMap selectLeaveById(int id) {
        return leaveMapper.selectLeaveById(id);
    }

    @Override
    public void setStatus(HashMap map) {
        leaveMapper.setStatus(map);
    }

    @Override
    public Leave searchLeaveByInstanceId(String instanceId) {
        return leaveMapper.searchLeaveByInstanceId(instanceId);
    }

    @Override
    public int deleteByid(Integer id) {
        Leave leave = leaveMapper.selectLeaveByid(id);
        approveService.deleteProcess(leave.getInstanceId());
        int i = leaveMapper.deleteByLId(id);
        if(leave.getStatus()==1){

        }
        return i;
    }


    private void startLeaveWorkFlow(int creatorId,String start,int day,String uuid) {
        //如果申请人为经理，则不需要创建工作流，直接生成一个uuid并完成审批即可
        int GMid = userMapper.searchGmId();
        if (creatorId==GMid){
            HashMap param = new HashMap();
            param.put("uuid", uuid);
            param.put("instanceId", UUID.randomUUID().toString());

            HashMap param1 = new HashMap();
            param1.put("uuid", uuid);
            param1.put("status", 1);

            leaveMapper.setInstanceId(param);
            leaveMapper.setStatus(param1);
            return ;
        }
//        HashMap info = userMapper.searchUserInfo(creatorId);
        long manager = (long) userMapper.searchDeptManagerId(creatorId);
        int isManager=0;
        if (manager==creatorId){
            isManager=1;
        }

        JSONObject json = new JSONObject();
        json.set("url", receiveNotify);
        json.set("createrId", creatorId);
        json.set("managerId", manager);
        json.set("isManager", isManager);
        json.set("gmId",GMid);
        json.set("dates", start);
        json.set("days", day);
        json.set("types", "leave");
        String url = workflow + "/leave/leaveRequest";
        HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString())
                .execute();
        if (resp.getStatus() == 200) {
            JSONObject json1 = JSONUtil.parseObj(resp.body());
            JSONObject result = JSONUtil.parseObj(json1.getStr("result"));
            String instanceId = result.getStr("instanceId");
            HashMap param = new HashMap();
            param.put("uuid", uuid);
            param.put("instanceId", instanceId);
            int row = leaveMapper.setInstanceId(param);
            if (row!=1){
                throw new OAException("保存会议工作流失败");
            }
        }
    }


}




